Master scope and encapsulation rules across classes and packages
Access Specifiers (also known as access modifiers) in Java define the scope and visibility of classes, constructors, variables, and methods. They control which other parts of your program can read or modify a specific member.
Restricts access strictly inside the same class file.
package com.example;
public class Student {
// Private variable cannot be accessed directly from outside
private String secretCode = "1234";
private void printSecret() {
System.out.println(secretCode); // Allowed: Inside the same class
}
}
Applied when no keyword is specified. Accessible to any class in the same package.
package com.example;
class Course { // Default class visibility
String courseName = "Java Programming"; // Default variable visibility
void display() { // Default method visibility
System.out.println("Course: " + courseName);
}
}
Accessible within the package and by child classes outside the package via inheritance.
package com.parent;
public class Person {
protected String nationalId = "ID-9901";
}
// In a different package:
package com.child;
import com.parent.Person;
public class Employee extends Person {
public void showId() {
// Allowed because Employee inherits from Person
System.out.println(nationalId);
}
}
Provides unrestricted access from any package in the application.
package com.example;
public class Application {
public String appName = "MyJavaApp";
public void start() {
System.out.println("App Started!");
}
}
Use this reference table to quickly review access rules across different boundaries:
| Access Modifier | Same Class | Same Package | Subclass (Diff Package) | World (Diff Package) |
|---|---|---|---|---|
| private | Yes | No | No | No |
| default (no modifier) | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |